/**
 * 模型字段迁移脚本
 * 将 type 字段迁移为 format 字段
 */

const fs = require('fs').promises;
const path = require('path');

// 项目目录
const PROJECTS_DIR = path.join(__dirname, '../../projects');

/**
 * 迁移单个项目
 */
async function migrateProject(projectPath, projectName) {
    const modelsJsonPath = path.join(projectPath, 'models', 'models.json');
    
    try {
        // 检查文件是否存在
        try {
            await fs.access(modelsJsonPath);
        } catch (error) {
            console.log(`⏭️  跳过 ${projectName}: models.json 不存在`);
            return { skipped: true };
        }
        
        // 读取文件
        const data = await fs.readFile(modelsJsonPath, 'utf-8');
        const config = JSON.parse(data);
        
        let modified = false;
        let migratedCount = 0;
        
        // 迁移每个模型
        config.models.forEach(model => {
            let modelModified = false;
            
            // 迁移 type -> format
            if (model.type !== undefined && !model.format) {
                model.format = model.type;
                delete model.type;
                modelModified = true;
                console.log(`  🔄 ${model.name}: type -> format (${model.format})`);
            }
            
            // 添加 originalName
            if (!model.originalName && model.filename) {
                model.originalName = model.filename;
                modelModified = true;
                console.log(`  ➕ ${model.name}: 添加 originalName`);
            }
            
            if (modelModified) {
                modified = true;
                migratedCount++;
            }
        });
        
        // 保存修改
        if (modified) {
            await fs.writeFile(modelsJsonPath, JSON.stringify(config, null, 2), 'utf-8');
            console.log(`✅ ${projectName}: 迁移完成，更新了 ${migratedCount} 个模型\n`);
            return { success: true, count: migratedCount };
        } else {
            console.log(`✓  ${projectName}: 无需迁移\n`);
            return { upToDate: true };
        }
        
    } catch (error) {
        console.error(`❌ ${projectName}: 迁移失败 - ${error.message}\n`);
        return { error: true, message: error.message };
    }
}

/**
 * 迁移所有项目
 */
async function migrateAll() {
    console.log('╔════════════════════════════════════════════════════════╗');
    console.log('║                                                        ║');
    console.log('║        🔄 模型字段迁移工具                            ║');
    console.log('║        type -> format                                  ║');
    console.log('║                                                        ║');
    console.log('╚════════════════════════════════════════════════════════╝\n');
    
    try {
        // 读取项目目录
        const dirs = await fs.readdir(PROJECTS_DIR);
        const projectDirs = dirs.filter(dir => dir.startsWith('project-'));
        
        if (projectDirs.length === 0) {
            console.log('⚠️  未找到任何项目\n');
            return;
        }
        
        console.log(`📂 找到 ${projectDirs.length} 个项目，开始迁移...\n`);
        
        // 统计信息
        const stats = {
            total: projectDirs.length,
            success: 0,
            upToDate: 0,
            skipped: 0,
            error: 0,
            totalModels: 0
        };
        
        // 迁移每个项目
        for (const dir of projectDirs) {
            const projectPath = path.join(PROJECTS_DIR, dir);
            const result = await migrateProject(projectPath, dir);
            
            if (result.success) {
                stats.success++;
                stats.totalModels += result.count;
            } else if (result.upToDate) {
                stats.upToDate++;
            } else if (result.skipped) {
                stats.skipped++;
            } else if (result.error) {
                stats.error++;
            }
        }
        
        // 输出统计信息
        console.log('╔════════════════════════════════════════════════════════╗');
        console.log('║                  迁移完成统计                          ║');
        console.log('╠════════════════════════════════════════════════════════╣');
        console.log(`║  总项目数:        ${stats.total.toString().padStart(3)}                                 ║`);
        console.log(`║  成功迁移:        ${stats.success.toString().padStart(3)} (更新了 ${stats.totalModels} 个模型)              ║`);
        console.log(`║  无需迁移:        ${stats.upToDate.toString().padStart(3)}                                 ║`);
        console.log(`║  跳过:            ${stats.skipped.toString().padStart(3)}                                 ║`);
        console.log(`║  失败:            ${stats.error.toString().padStart(3)}                                 ║`);
        console.log('╚════════════════════════════════════════════════════════╝\n');
        
        if (stats.error > 0) {
            console.log('⚠️  部分项目迁移失败，请检查上方错误信息\n');
        } else if (stats.success > 0) {
            console.log('✅ 所有项目迁移成功！请重启服务以应用更改。\n');
        } else {
            console.log('✓  所有项目都已是最新版本！\n');
        }
        
    } catch (error) {
        console.error('\n❌ 迁移过程发生错误:', error.message);
        console.error(error.stack);
    }
}

// 运行迁移
migrateAll().catch(error => {
    console.error('\n❌ 致命错误:', error);
    process.exit(1);
});

